#  练习，输入搜索的内容
#  将内容形成url链接后向百度发请求，
#  得到网页信息后保存为‘xxx.html’
#  提示：https://www.baidu.com/s?wd=搜索的关键字的url编码
from urllib import request
from urllib.parse import urlencode

keyword = input('请输入搜索内容：')
query_string = urlencode({'wd': keyword})
# 1、字符串相加
# url = 'http://www.baidu.com/s?' + query_string
# 2、字符串格式化（占位符 '%s'）
# url = 'http://www.baidu.com/%s?' % query_string
# 3、str.format() 方法
url = 'http://www.baidu.com/s?{}'.format(query_string)

print('url:', url)

headers = {
    'User-Agent':
        "Mozilla/5.0 (X11; Linux x86_64) "
        "AppleWebKit/537.36 (KHTML, like Gecko) "
        "Chrome/80.0.3987.116 Safari/537.36"
}
req = request.Request(url, headers=headers)
resp = request.urlopen(req)
print('Status', resp.getcode())
b = resp.read()

with open(keyword+'.html', 'wb') as fw:
    fw.write(b)